<?php
	class crud_holegolfcourse {
		function getAllHoleGolfCourse(){
			$start	= (isset($_REQUEST['start']))? $_REQUEST['start'] : 0;
			$limit	= (isset($_REQUEST['limit']))? $_REQUEST['limit'] : 10;
			$sql = "select 
							ID,
							HOLE,
							LENGTH,
							PAR,
							GOLF_COURSE_ID
					from hole_golf_course where 1=1 and GOLF_COURSE_ID='".$_GET['query']."'";
			$sqlCount = "select 
							count(*) as total
					from hole_golf_course where 1=1 and GOLF_COURSE_ID='".$_GET['query']."'";
			$sql .= " order by `HOLE`";
			// $sql .= " order by `HOLE` LIMIT ".$limit." OFFSET ".$start;
			$resultSql = Yii::app()->db->createCommand($sql)->queryAll();
			$resultCount = Yii::app()->db->createCommand($sqlCount)->queryAll();
			$response = array();
			foreach ($resultSql as $val => $r){
				array_push($response, array(
					"ID"=>$r['ID']
					, "HOLE"=>intval($r['HOLE'])
					, "LENGTH"=>floatval($r['LENGTH'])
					, "PAR"=>intval($r['PAR'])
					, "GOLF_COURSE_ID"=>$r['GOLF_COURSE_ID']
					)
				);
			}
			echo '{success:true,results: '.$resultCount[0]['total'].',rows:'.json_encode($response).'}';
		}
		
		function insert(){
			$model = new HoleGolfCourse;
			$transaction = Yii::app()->db->beginTransaction();
			try {
				$model->HOLE = $_POST['hole-inputEl'];
				$model->LENGTH = $_POST['length-inputEl'];
				$model->PAR = $_POST['par-inputEl'];
				$model->GOLF_COURSE_ID = $_POST['id_golfcourse-inputEl'];
				$model->save();
				$transaction->commit();
				$feedback = '{"feedback":[{"message":"Insert Sukses","code":"1","ID":"'.$model->ID.'"}]}';
			} catch (Exception $e) {
				// echo $e;
				$transaction->rollback();
				$feedback = '{"feedback":[{"message":"Insert Gagal","code":"0"}]}';
			}
			echo $feedback;
		}
		
		function update(){
			$model = HoleGolfCourse::model()->findByPk($_POST['id-inputEl']);
			$transaction = Yii::app()->db->beginTransaction();
			try {
				$model->HOLE = $_POST['hole-inputEl'];
				$model->LENGTH = $_POST['length-inputEl'];
				$model->PAR = $_POST['par-inputEl'];
				$model->GOLF_COURSE_ID = $_POST['id_golfcourse-inputEl'];
				$model->save();
				$transaction->commit();
				$feedback = '{"feedback":[{"message":"Update Sukses","code":"1","ID":"'.$model->ID.'"}]}';
			} catch (Exception $e) {
				// echo $e;
				$transaction->rollback();
				$feedback = '{"feedback":[{"message":"Update Gagal","code":"0"}]}';
			}
			echo $feedback;
		}
		
		function delete(){
			$model = HoleGolfCourse::model()->findByPk($_POST['id']);
			$transaction = Yii::app()->db->beginTransaction();
			try {
				$model->delete();
				$transaction->commit();
				$feedback = '{"feedback":[{"message":"Player dengan ID : '.$model->ID.' Berhasil Dihapus","code":"1","ID":"'.$model->ID.'"}]}';
			} catch (Exception $e) {
				// echo $e;
				$transaction->rollback();
				$feedback = '{"feedback":[{"message":"Player dengan ID : '.$model->ID.' Gagal Dihapus","code":"0"}]}';
			}
			echo $feedback;
		}
	}
?>